<template>
  <slot />
  <el-image-viewer
    v-if="showPreview"
    show-progress
    hide-on-click-modal
    :url-list="images[current?.group || ''] || []"
    :initial-index="current.index"
    @close="showPreview = false"
  />
</template>

<script setup>
import { ref, provide } from 'vue';
import { ElImageViewer } from 'element-plus';

const props = defineProps({
  defaultReader: String,
  readerOption: Object,
});

let __GROUP_ID__ = 20000;
const images = ref({});
const current = ref({});
const showPreview = ref(false);

const register = (group, src) => {
  group = group || __GROUP_ID__++;
  if (!images.value[group]) images.value[group] = [];
  let index = images.value[group].indexOf(src);
  if (index === -1) {
    index = images.value[group].length;
    images.value[group].push(src);
  }

  const remove = () => {
    if (!images.value[group]) return;
    images.value[group].splice(index, 1);
    if (images.value[group].length === 0) {
      delete images.value[group];
    }
  };

  return { index, group, remove };
};

const open = (group, index = 0) => {
  current.value = { group, index };
  showPreview.value = true;
};

const go = (index) => {
  current.value = { ...current.value, index };
};

provide('ImageContext', {
  enable: true,
  defaultReader: props.defaultReader,
  readerOption: props.readerOption,
  register,
  open,
  go,
});
</script>
